﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using System.Windows.Media.Imaging;
using System.IO;
//using System.Windows.Shapes.Path;
//using System.IO.Path;

namespace MiniChat
{
    public partial class MainPage : PhoneApplicationPage
    {
       
        public static String hostip { set; get; }
        public static int hostport { set; get; }
        public static String UserName { set; get; }
        public static String PassWord { set; get; }
        public static bool noneclosesock = false;
        public static bool invokereturn = false;

        public static int buffersize = 1024;

        public MainPage()
        {
            //hostip = "112.213.87.154";
            //hostip = "192.168.1.35";
            hostip = "192.168.1.100";
            hostport = 5203;
            //hostip = "192.168.133.1";
            InitializeComponent();
            CGlobalVariable.lsbContacts = lsbContacts;
        }

        private void cmdLogin_Click(object sender, RoutedEventArgs e)
        {
            txtUserName.Background = new SolidColorBrush(Colors.White);
            txtPassword.Background = new SolidColorBrush(Colors.White);
            UserName = txtUserName.Text;
            if (UserName == "") { txtUserName.Background = new SolidColorBrush(Colors.Red); txtUserName.Focus(); return; }
            PassWord = txtPassword.Password;
            CGlobalVariable.UserName = UserName;
            if (PassWord == "") { txtPassword.Background = new SolidColorBrush(Colors.Red); txtPassword.Focus(); return; }
            pnLoading.Visibility = System.Windows.Visibility.Visible;
            Thread t = new Thread(new ThreadStart(Login));
            t.Start();
            //NavigationService.Navigate(new Uri("/MiniChat.xaml",UriKind.Relative));
        }

        public void Login() 
        {
            txtNotice.Dispatcher.BeginInvoke((Action)(() => { txtNotice.Text = "Begin connect to server ..."; }));
            Socket s = new Socket(AddressFamily.InterNetwork,
                                  SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ip = new IPEndPoint(IPAddress.Parse(hostip), hostport);
            SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
            socketEventArg.UserToken = s;
            socketEventArg.RemoteEndPoint = ip;
            socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(socketEventArg_Completed);
            s.ConnectAsync(socketEventArg);
        }

        void socketEventArg_Completed(object sender, SocketAsyncEventArgs e)
        {   
            Socket s = (Socket) sender;
            if (e.SocketError != SocketError.Success)
            {
                txtNotice.Dispatcher.BeginInvoke((Action)(() => { txtNotice.Text = "Server down. Can't find login server."; }));
                Thread.Sleep(2000);
                pnLoading.Dispatcher.BeginInvoke((Action)(() => { pnLoading.Visibility = System.Windows.Visibility.Collapsed; }));
                return;
            }
            else
            {
                txtNotice.Dispatcher.BeginInvoke((Action)(() => { txtNotice.Text = "Loading user informations."; }));
                Thread.Sleep(1000);
                //pnLoading.Dispatcher.BeginInvoke((Action)(() => { pnLoading.Visibility = System.Windows.Visibility.Collapsed; }));
                
                //Gởi

                SocketAsyncEventArgs ed = new SocketAsyncEventArgs();
                byte[] buffer = Encoding.UTF8.GetBytes("login:" + UserName + ":" + PassWord);
                ed.SetBuffer(buffer, 0, buffer.Length);
                s.SendAsync(ed);
                CGlobalVariable.connectedsock = (Socket)sender;
                Thread t = new Thread(new ThreadStart(reldata));
                t.Start();
              
            }

            
           
        }

        void reldata()
        {
            //Nhận
            SocketAsyncEventArgs releventag = new SocketAsyncEventArgs();
            var responseBuffer = new byte[1024];
            releventag.SetBuffer(responseBuffer, 0, 1024);
            releventag.Completed += new EventHandler<SocketAsyncEventArgs>(releventag_Completed);
            CGlobalVariable.connectedsock.ReceiveAsync(releventag);
        }


        void releventag_Completed(object sender, SocketAsyncEventArgs e)
        {
            var message = Encoding.UTF8.GetString(e.Buffer, 0, e.BytesTransferred);
            var listcommand = Ullity.Split(message, "\n");           
            foreach (string strdata in listcommand)
            {
                Client.ProcessMessage(strdata, CGlobalVariable.connectedsock, ref CGlobalVariable.Logged);
                if (strdata.Contains("loginstatus"))
                {
                    if (CGlobalVariable.Logged == false)
                    {
                        txtNotice.Dispatcher.BeginInvoke((Action)(() =>
                        {
                            txtNotice.Text = "Invalid username or password";
                        }));
                        Thread.Sleep(3000);
                        pnLoading.Dispatcher.BeginInvoke((Action)(() =>
                        {
                            if (pnLoading.Visibility != System.Windows.Visibility.Collapsed)
                            {
                                pnLoading.Visibility = System.Windows.Visibility.Collapsed;
                            }
                        }));
                    }
                    else
                    {
                        this.Dispatcher.BeginInvoke((Action)(() =>
                        {
                            pnLogin.Visibility = System.Windows.Visibility.Collapsed;
                            pvMiniChat.Visibility = System.Windows.Visibility.Visible;
                            noneclosesock = true; 
                        }));
                        invokereturn = true;
                    }
                }
            }
            reldata();
        }

        
      
     
    }
}